var express = require('express');
var xlsx = require('node-xlsx')
var fs = require('fs')
var AnswerModel = require('../db/answerModel')
var QuestModel = require('../db/questModel')

module.exports = function (req, res) {
    var peopleNumber = 0
    var result = []
    var maxOptionNumbers = 0
    var questid = req.params.id
    QuestModel.findOne({id: parseInt(questid)}, function (error, quest) {
        if (quest) {
            maxOptionNumbers = 0
            for (let i = 0; i < quest.questions.length; i++) {
                if (quest.questions[i].type !== 2 && quest.questions[i].option.length > maxOptionNumbers) {
                    maxOptionNumbers = quest.questions[i].option.length
                }
            }
        } else {
            res.status(400).send({
                status: 400,
                message: "问卷不存在"
            })
        }
    })
    QuestModel.findOne({id: parseInt(questid)}, async function (error, quest) {
            if (quest) {
                //找到了问卷
                await AnswerModel.find({questId: questid}, function (error, answer) {
                    for (let i = 0; i < quest.questions.length; i++) {
                        var tmp = []
                        tmp[0] = i + 1
                        // if (quest.questions[i].type === 2) {
                        //     continue
                        // }
                        //如果为非必填，统计填写人数
                        if (quest.questions[i].isNecessary === false) {
                            peopleNumber = 0
                        }
                        //找到最大选项个数
                        // if (quest.questions[i].option.length > maxOptionNumbers) {
                        //     maxOptionNumbers = quest.questions[i].option.length
                        // }
                        //问题共有几个选项,选项数量初始化为0
                        if (quest.questions[i].type !== 2) {
                            for (let j = 1; j <= quest.questions[i].option.length; j++) {
                                // tmp.options.push({number: 0})
                                tmp[j] = 0
                            }
                        }
                        //遍历该问题的所有答案
                        for (let j = 0; j < answer.length; j++) {

                            if (answer[j].answers[i].answer === null) {
                                peopleNumber++
                                continue
                            }
                            //如果为单选
                            if (quest.questions[i].type === 0) {
                                tmp[answer[j].answers[i].answer]++
                            } else if (quest.questions[i].type === 1) {
                                //如果为多选
                                for (let k = 0; k < answer[j].answers[i].answer.length; k++) {
                                    tmp[answer[j].answers[i].answer[k]]++
                                }
                            } else {
                                tmp[1] = "文本题不支持统计哦~"
                            }
                        }
                        //如果非必填 加入填写人数
                        if (quest.questions[i].isNecessary === false) {
                            tmp[maxOptionNumbers + 1] = answer.length - peopleNumber
                        } else {
                            tmp[maxOptionNumbers + 1] = answer.length
                        }
                        result.push(tmp)
                    }

                    //构建数组
                    var data = []
                    var s = ["题目序号"]

                    for (let i = 1; i <= maxOptionNumbers; i++) {
                        s.push("选项" + i)
                    }
                    s.push("填写人数")
                    data.push(s)

                    for (let i = 0; i < result.length; i++) {
                        data.push(result[i])
                    }
                    data.push([])
                    data.push(["填写总人数", answer.length])
                    const options = {'!cols': [{wch: 11}]};
                    //写入xlsx
                    var buffer = xlsx.build([{name: quest.title, data: data}], options);
                    fs.writeFileSync("./download/" + questid + ".xlsx", buffer, 'binary');
                })

                var filepath = "./download/" + questid + ".xlsx"

                //下载文件
                res.set({
                    "Content-Disposition": "attachment;filename=" + encodeURI(filepath),
                    "Content-Type": "application/vnd.openxmlformats;charset=utf-8"
                })
                res.download(filepath, function (error) {
                    if (error) {
                        res.status(400).send({
                            status: 400,
                            message: "下载失败"
                        })
                    } else {
                        fs.unlinkSync(filepath)
                    }
                })

            } else {
                //问卷没有找到
                res.status(400).send({
                    status: 400,
                    message: "问卷不存在"
                })
            }
        }
    )
}